package com.tkjt.pms.modules.report.controller;

import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tkjt.pms.common.entity.TkIndexValue;
import com.tkjt.pms.modules.scoring.mapper.TkScoringMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.tkjt.pms.calc.core.AuditStatusWatcher;
import com.tkjt.pms.common.vos.TkIndexReportVO;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.common.service.TkIndexReportService;
import com.tkjt.pms.modules.report.service.ReportCreator;
import com.tkjt.pms.modules.report.vo.DatagridVO;
import com.tkjt.pms.modules.report.vo.IndexReportParam;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/pms/report")
public class IndexReportController {

	@Value(value = "${pms.report.path}")
	private String reportPath;
	
	@Autowired
	private ReportCreator reportCreator;
	@Autowired
	private TkIndexReportService tkIndexReportService;
	@Autowired
	private TkDataConfigService tkDataConfigService;
    @Autowired
    private AuditStatusWatcher auditStatusWatcher;

	@Autowired
	private TkScoringMapper tkScoringMapper;

	@GetMapping(value= "/list")
	public Result<?> queryPageList(TkIndexReportVO kIndexReport, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(loginUser==null) {
			return Result.error("用户非法！");
		}
		kIndexReport.setPageNo(pageNo);
		kIndexReport.setPageSize(pageSize);
		try {
			return tkIndexReportService.list(loginUser,kIndexReport);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("获取数据异常");
		}
	}

	/**
	 * 绩效报表详情-列表条件
	 * 表头信息
	 * @return
	 */
	@RequestMapping("detailConditions")
	public Result<?> detailConditions(@RequestBody DatagridVO datagridVO){
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			return reportCreator.detailConditions(loginUser,datagridVO);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("获取数据异常");
		}
	}
	/**
	 * 绩效报表详情-列表信息
	 * 表头信息
	 * @return
	 */
	@RequestMapping("detailDatagrid")
	public Result<?> detailDatagrid(@RequestBody DatagridVO datagridVO){
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			return reportCreator.detailDatagrid(loginUser,datagridVO);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("获取数据异常");
		}
	}

	/**
	 * 绩效考核报表生成
	 * @param param
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/creator")
	public Result<Object> creator(@RequestBody IndexReportParam param, HttpServletRequest request) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(loginUser==null) {
			return Result.error("用户非法！");
		}
		try {
			String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
			Set<String> reportCodes = new HashSet<>();
			if(StringUtils.isEmpty(param.getReportCode())){
				reportCodes.addAll(tkIndexReportService.selectReportCodes(param.getIndexYearMonth(), dataType));
			}else{
				reportCodes.add(param.getReportCode());
			}

			String mirrorCode = "MC" + param.getIndexYearMonth();
			if(auditStatusWatcher.isOngoingMirror(mirrorCode, null, dataType)) {
				return Result.error("审核数据镜像任务正在运行，暂不可生成报表，请稍后再试...");
			}
			
			Map<String, Object> updateParam = new HashMap<>();
			updateParam.put("reportCodes",reportCodes);
			updateParam.put("indexYearMonth",param.getIndexYearMonth());
			//生成中
			updateParam.put("reportStatus","2");
			updateParam.put("dataType",dataType);
			
			tkIndexReportService.updateReporByParam(updateParam);
			reportCreator.doCreator(param.getIndexYearMonth(), reportCodes,loginUser);
			return Result.ok("绩效报表重新生成启动.....");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("获取数据异常");
		}

		
	}

	@GetMapping(value = "/exportXls")
	public void xlsGet(@RequestParam(name = "indexYearMonth") String indexYearMonth, @RequestParam(name = "reportCode") String reportCode, HttpServletRequest request) {
		log.info("index report export params : indexYearMonth={}, reportCode={}", indexYearMonth, indexYearMonth);

	}

	@PostMapping(value = "/exportXls")
	public void xlsPost(@RequestBody IndexReportParam param, HttpServletRequest request) {
		log.info("index report export params : indexYearMonth={}, reportCode={}", param.getIndexYearMonth(), param.getReportCode());

	}

	@GetMapping(value = "/exportXlsx/**")
	public void xlsxGet(@RequestParam(name = "indexYearMonth") String indexYearMonth, @RequestParam(name = "reportCode") String reportCode, @RequestParam(name = "isTotal") String isTotal,HttpServletResponse response) throws Exception {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if("RIS".equals(reportCode)){
			String orgCode = loginUser.getOrgCode();
			List<String> rcurrentUserRoleCodes = tkScoringMapper.selectRolesByUserName(loginUser.getUsername());
			if(rcurrentUserRoleCodes.contains("ykgm") || rcurrentUserRoleCodes.contains("ykaudit") || rcurrentUserRoleCodes.contains("ykkpiowner")){
				List<String> orgCodes = tkScoringMapper.selectOrgCodesByUserName(loginUser.getUsername());
				for(String item : orgCodes){
					if(!item.equals("A01A01")){
						orgCode = item;
						continue;
					}
				}
			}
			if(isTotal.equals("true")){
				reportCode = "isTotal@"+loginUser.getUsername()+"@"+orgCode;
			}else{
				reportCode = loginUser.getUsername()+"@"+orgCode;
			}

		}
		String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
		this.exportReportExcel(indexYearMonth, reportCode, dataType,response);
	}

	@PostMapping(value = "/exportXlsx/**")
	public void xlsxPost(@RequestBody IndexReportParam param, HttpServletResponse response) throws Exception {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String indexYearMonth = param.getIndexYearMonth();
		String reportCode = param.getReportCode();
		if("RIS".equals(reportCode)){
			reportCode = loginUser.getUsername()+"@"+loginUser.getOrgCode();
		}
		String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
		this.exportReportExcel(indexYearMonth, reportCode, dataType,response);
	}

	private void exportReportExcel(String indexYearMonth, String reportCode,String dataType, HttpServletResponse response) throws Exception {

		String excelFile = "";
		{
			StringBuilder sbuilder = new StringBuilder(reportPath);
			sbuilder.append("//").append(indexYearMonth).append("-").append(reportCode).append("-").append(dataType).append(".xlsx");
			excelFile = sbuilder.toString();
		}
		// 其余处理略
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			File file = new File(excelFile);
			if (!file.exists()) {
				throw new Exception("file not exist, file=" + excelFile);
			}
			response.setContentType("application/force-download");// 设置强制下载不打开            
			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
			inputStream = new BufferedInputStream(new FileInputStream(file));
			outputStream = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, len);
			}
			response.flushBuffer();
			Map<String, Object> updateParam = new HashMap<>();
			updateParam.put("reportCode",reportCode);
			updateParam.put("dataType",dataType);
			updateParam.put("indexYearMonth",indexYearMonth);
			//已下载-去掉该状态
			//updateParam.put("reportStatus","4");
			updateParam.put("downloadTimes","downloadTimes");
			updateParam.put("downloadDate",new Date());
			updateParam.put("updateDate",new Date());
			tkIndexReportService.updateReporByParam(updateParam);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("export report excel error, indexYearMonth=" + indexYearMonth + ",reportCode" + reportCode, e);
			Map<String, Object> updateParam = new HashMap<>();
			updateParam.put("dataType",dataType);
			updateParam.put("reportCode",reportCode);
			updateParam.put("indexYearMonth",indexYearMonth);
			//有错误
			updateParam.put("reportStatus","0");
			tkIndexReportService.updateReporByParam(updateParam);
			throw new Exception("报表下载失败");
		} finally {
			this.closeStream(inputStream);
			this.closeStream(outputStream);
		}

	}

	private void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}
	
}
